<template>
	<view class="page-container">
		<!-- 顶部导航栏 -->
		<view class="top-navbar">
			<scroll-view class="nav-scroll" scroll-x="true" show-scrollbar="false">
				<view class="nav-items">
					<view v-for="(nav, index) in navList" :key="index" class="nav-item"
						:class="{ active: currentNav === nav.key }" @click="switchNav(nav.key)">
						<text class="nav-text">{{ nav.name }}</text>
						<view class="nav-indicator" v-if="currentNav === nav.key"></view>
					</view>
				</view>
			</scroll-view>

			<!-- 天气 -->
			<view class="weather-info" @click="refreshWeather">
				<text class="weather-temp">{{ weatherData.temp }}℃ {{ weatherData.weather }}</text>
				<text class="weather-location">{{ weatherData.city }} PM{{ weatherData.pm25 }}</text>
				<text class="weather-refresh" v-if="weatherLoading">⟳</text>
			</view>
		</view>

		<!-- 搜索栏 -->
		<view class="search-bar">
			<view class="search-container">
				<view class="search-icon">🔍</view>
				<input class="search-input" placeholder="搜索关键词" placeholder-class="placeholder" v-model="searchKeyword"
					@confirm="handleSearch" @input="handleSearchInput" />
				<view class="search-actions">
					<text class="search-action" @click="handleScan">扫码</text>
					<text class="search-action" @click="handleVoice">语音</text>
				</view>
			</view>
		</view>

		<view class="update-notice" v-if="showUpdateNotice">
			<text class="notice-text">为您更新了{{ updateCount }}条内容</text>
			<text class="notice-time">{{ currentTime }}</text>
			<text class="notice-close" @click="closeUpdateNotice">×</text>
		</view>

		<!-- 内容 -->
		<scroll-view class="content-wrapper" scroll-y="true" :refresher-enabled="true"
			:refresher-triggered="refresherTriggered" @refresherrefresh="onRefresherRefresh"
			@refresherrestore="onRefresherRestore" @refresherabort="onRefresherAbort" @scrolltolower="onReachBottom">
			<view class="content">
				<!-- 置顶新闻 -->
				<view v-if="showTopNews && topNews.length > 0" class="top-news-section">
					<view class="section-title">
						<text class="section-title-text">置顶新闻</text>
					</view>
					<view class="top-news-list">
						<view v-for="(item, index) in topNews" :key="'top-' + item.id" class="top-news-item">
							<CustomTextView :card-info="item" :title="item.title" :isTop="true" :author="item.author"
								:comments="item.comments" :time="item.time" :index="index" :modetype="item.modetype"
								@itemClick="handleNewsClick" @itemAction="handleNewsAction">
								<template v-slot:image v-if="item.modetype === 2">
									<view class="single-image-container">
										<image class="single-image" :src="getImageUrl(item.imageUrl)" mode="aspectFill">
										</image>
									</view>
								</template>
								<template v-slot:images v-if="item.modetype === 3">
									<view class="multi-images-container">
										<view v-for="(img, imgIndex) in getMultiImages(item.images)" :key="imgIndex"
											class="multi-image-item">
											<image class="multi-image"
												:src="img ? getImageUrl(img) : '/static/图片加载错误.png'" mode="aspectFill">
											</image>
										</view>
									</view>
								</template>
							</CustomTextView>
						</view>
					</view>
				</view>

				<!-- 普通新闻列表 -->
				<view class="normal-news-section">
					<view v-if="filteredData.length === 0 && !isLoading" class="empty-state">
						<image class="empty-image" src="/static/empty.png" mode="aspectFit"></image>
						<text class="empty-text">暂无相关内容</text>
					</view>

					<view v-for="(item, index) in filteredData" :key="item.id" class="card-wrapper">
						<!-- 广告插槽 -->
						<view v-if="shouldShowAd(index)" class="ad-card">
							<AdCard :ad-data="getRandomAd()" @adClick="handleAdClick" @adClose="handleAdClose"></AdCard>
						</view>

						<!-- 无图模式 (modetype: 1) -->
						<CustomTextView v-if="item.modetype === 1" :card-info="item" :title="item.title"
							:isTop="item.isTop" :author="item.author" :comments="item.comments" :time="item.time"
							:index="index" :modetype="item.modetype" @itemClick="handleNewsClick"
							@itemAction="handleNewsAction">
						</CustomTextView>

						<!-- 单图模式 (modetype: 2) -->
						<CustomTextView v-else-if="item.modetype === 2" :card-info="item" :title="item.title"
							:isTop="item.isTop" :author="item.author" :comments="item.comments" :time="item.time"
							:index="index" :modetype="item.modetype" @itemClick="handleNewsClick"
							@itemAction="handleNewsAction">
							<template v-slot:image>
								<view class="single-image-container">
									<image class="single-image" :src="getImageUrl(item.imageUrl)" mode="aspectFill">
									</image>
								</view>
							</template>
						</CustomTextView>

						<!-- 多图模式 (modetype: 3) -->
						<CustomTextView v-else-if="item.modetype === 3" :card-info="item" :title="item.title"
							:isTop="item.isTop" :author="item.author" :comments="item.comments" :time="item.time"
							:index="index" :modetype="item.modetype" @itemClick="handleNewsClick"
							@itemAction="handleNewsAction">
							<template v-slot:images>
								<view class="multi-images-container">
									<view v-for="(img, imgIndex) in getMultiImages(item.images)" :key="imgIndex"
										class="multi-image-item">
										<image class="multi-image" :src="img ? getImageUrl(img) : '/static/图片加载错误.png'"
											mode="aspectFill"></image>
									</view>
								</view>
							</template>
						</CustomTextView>
					</view>

					<view class="load-more" v-if="isLoading">
						<text class="load-more-text">加载中...</text>
					</view>
					<view class="no-more" v-if="!hasMore && cardData.length > 0">
						<text class="no-more-text">没有更多内容了</text>
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import CustomTextView from "/components/cardViewText.vue"
	import AdCard from "/components/AdCard.vue"
	import newsData from "../../Data/news.json"

	const mockApi = {
		getNewsCategories: () => {
			return new Promise((resolve) => {
				setTimeout(() => {
					resolve({
						code: 200,
						data: [{
								key: 'hot',
								name: '要闻'
							},
							{
								key: 'recommend',
								name: '推荐'
							},
							{
								key: 'follow',
								name: '关注'
							},
							{
								key: '24h',
								name: '24小时'
							},
							{
								key: 'entertainment',
								name: '娱乐'
							},
							{
								key: 'finance',
								name: '财经'
							},
							{
								key: 'sports',
								name: '体育'
							},
							{
								key: 'tech',
								name: '科技'
							}
						]
					});
				}, 500);
			});
		},

		getWeather: (city = '泉州') => {
			return new Promise((resolve) => {
				setTimeout(() => {
					const weatherTypes = ['晴', '多云', '小雨', '阴', '雷阵雨'];
					resolve({
						code: 200,
						data: {
							city: city,
							temp: Math.floor(Math.random() * 15) + 5,
							weather: weatherTypes[Math.floor(Math.random() * weatherTypes
								.length)],
							pm25: Math.floor(Math.random() * 100) + 30
						}
					});
				}, 800);
			});
		},

		getNewsList: (category, page = 1, pageSize = 10) => {
			return new Promise((resolve) => {
				setTimeout(() => {
					const allNews = newsData.newsData || [];
					const startIndex = (page - 1) * pageSize;
					const endIndex = startIndex + pageSize;

					let filteredNews = allNews;
					if (category !== 'hot') {
						filteredNews = allNews.filter((_, index) => index % 3 === 0);
					}

					const paginatedNews = filteredNews.slice(startIndex, endIndex);
					const hasMore = endIndex < filteredNews.length;

					resolve({
						code: 200,
						data: {
							list: paginatedNews,
							hasMore: hasMore,
							total: filteredNews.length
						}
					});
				}, 1000);
			});
		},

		getAdData: () => {
			return new Promise((resolve) => {
				setTimeout(() => {
					const ads = [{
							id: 1,
							title: "新品上市 | 限时优惠",
							desc: "全新产品体验，立即购买享受专属折扣",
							image: "/static/ad1.jpg",
							bgColor: "#f8f9ff",
							link: "/pages/ad/detail?id=1"
						},
						{
							id: 2,
							title: "品牌特惠活动",
							desc: "多款商品限时特价，错过再等一年",
							image: "/static/ad2.jpg",
							bgColor: "#f9fff9",
							link: "/pages/ad/detail?id=2"
						},
						{
							id: 3,
							title: "会员专属福利",
							desc: "开通会员享更多优惠和特权",
							image: "/static/ad3.jpg",
							bgColor: "#fff9f9",
							link: "/pages/ad/detail?id=3"
						}
					];
					resolve({
						code: 200,
						data: ads
					});
				}, 500);
			});
		}
	};

	export default {
		name: "cardViewPage",
		components: {
			CustomTextView,
			AdCard
		},
		data() {
			return {
				navList: [],
				currentNav: 'hot',
				searchKeyword: '',
				showUpdateNotice: false,
				updateCount: 0,
				currentTime: this.formatTime(new Date()),
				weatherData: {
					city: '泉州',
					temp: '--',
					weather: '--',
					pm25: '--'
				},
				weatherLoading: false,
				refresherTriggered: false,
				isLoading: false,
				hasMore: true,
				currentPage: 1,
				cardData: [],
				topNews: [],
				showTopNews: true,
				adList: [],
				adPosition: 3,
				searchTimer: null
			};
		},
		computed: {
			filteredData() {
				if (!this.searchKeyword.trim()) {
					return this.cardData.filter(item => !item.isTop);
				}
				const keyword = this.searchKeyword.toLowerCase();
				return this.cardData.filter(item =>
					!item.isTop && (
						item.title.toLowerCase().includes(keyword) ||
						item.author.toLowerCase().includes(keyword)
					)
				);
			}
		},
		methods: {
			async fetchNewsCategories() {
				try {
					const result = await mockApi.getNewsCategories();
					if (result.code === 200) {
						this.navList = result.data;
					}
				} catch (error) {
					console.error('获取新闻分类失败:', error);
				}
			},

			async fetchWeatherData() {
				try {
					this.weatherLoading = true;
					const result = await mockApi.getWeather();
					if (result.code === 200) {
						this.weatherData = result.data;
					}
				} catch (error) {
					console.error('获取天气数据失败:', error);
				} finally {
					this.weatherLoading = false;
				}
			},

			async fetchNewsData(category = 'hot', page = 1, isRefresh = false) {
				try {
					this.isLoading = true;
					const result = await mockApi.getNewsList(category, page);

					if (result.code === 200) {
						const newsList = result.data.list;

						if (isRefresh || page === 1) {
							this.cardData = newsList;
							this.topNews = newsList.filter(item => item.isTop);
						} else {
							this.cardData = [...this.cardData, ...newsList];
						}

						this.hasMore = result.data.hasMore;
						this.currentPage = page;

						if (isRefresh) {
							this.updateCount = newsList.length;
							this.showUpdateNotice = true;
							this.currentTime = this.formatTime(new Date());
							setTimeout(() => {
								this.showUpdateNotice = false;
							}, 3000);
						}
					}
				} catch (error) {
					console.error('获取新闻数据失败:', error);
					this.showToast('加载失败', 'error');
				} finally {
					this.isLoading = false;
				}
			},

			async fetchAdData() {
				try {
					const result = await mockApi.getAdData();
					if (result.code === 200) {
						this.adList = result.data;
					}
				} catch (error) {
					console.error('获取广告数据失败:', error);
				}
			},

			getRandomAd() {
				if (this.adList.length === 0) return null;
				const randomIndex = Math.floor(Math.random() * this.adList.length);
				return this.adList[randomIndex];
			},

			shouldShowAd(index) {
				return index > 0 && index % 5 === this.adPosition % 4;
			},

			getImageUrl(imageUrl) {
				return imageUrl || '/static/图片加载错误.png';
			},

			getMultiImages(images) {
				if (!images || !Array.isArray(images)) {
					return [null, null, null];
				}
				const result = [...images];
				while (result.length < 3) {
					result.push(null);
				}
				return result.slice(0, 3);
			},

			switchNav(navKey) {
				this.currentNav = navKey;
				this.currentPage = 1;
				this.fetchNewsData(navKey, 1, true);
				this.showToast(`切换到: ${this.navList.find(nav => nav.key === navKey)?.name}`);
			},

			handleSearch() {
				if (this.searchKeyword.trim()) {
					this.showToast(`搜索: ${this.searchKeyword}`);
				}
			},

			handleSearchInput() {
				if (this.searchTimer) {
					clearTimeout(this.searchTimer);
				}
				this.searchTimer = setTimeout(() => {
					if (this.searchKeyword.trim()) {
						console.log('搜索关键词:', this.searchKeyword);
					}
				}, 500);
			},

			handleScan() {
				uni.scanCode({
					success: (res) => {
						this.showToast(`扫描结果: ${res.result}`);
					},
					fail: () => {
						this.showToast('扫码失败', 'error');
					}
				});
			},

			handleVoice() {
				this.showToast('语音搜索功能');
			},

			async refreshWeather() {
				await this.fetchWeatherData();
				this.showToast('天气已更新');
			},

			closeUpdateNotice() {
				this.showUpdateNotice = false;
			},

			handleNewsClick(data) {
				console.log('新闻点击:', data);
				uni.navigateTo({
					url: `/pages/newsDetail/newsDetail?id=${data.id}`
				});
			},

			handleNewsAction(data) {
				const actionText = {
					'share': '分享',
					'collect': '收藏',
					'report': '举报'
				} [data.action];
				this.showToast(`已${actionText}`);
			},

			handleAdClick(ad) {
				this.showToast(`跳转到: ${ad.title}`);
			},

			handleAdClose(ad) {
				this.showToast('已关闭广告');
			},

			showToast(message, type = 'info') {
				uni.showToast({
					title: message,
					icon: type === 'error' ? 'error' : 'none',
					duration: 2000
				});
			},

			formatTime(date) {
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				return `${hours}:${minutes}`;
			},

			onRefresherRefresh() {
				this.refresherTriggered = true;
				this.refreshData();
			},

			onRefresherRestore() {
				this.refresherTriggered = false;
			},

			onRefresherAbort() {
				this.refresherTriggered = false;
			},

			async refreshData() {
				try {
					this.adPosition = Math.floor(Math.random() * 10);
					await Promise.all([
						this.fetchWeatherData(),
						this.fetchNewsData(this.currentNav, 1, true),
						this.fetchAdData()
					]);
				} catch (error) {
					console.error('刷新数据失败:', error);
					this.showToast('刷新失败', 'error');
				} finally {
					this.refresherTriggered = false;
				}
			},

			async loadMoreData() {
				if (this.isLoading || !this.hasMore) return;
				await this.fetchNewsData(this.currentNav, this.currentPage + 1);
			},

			onReachBottom() {
				this.loadMoreData();
			}
		},

		onLoad() {
			this.fetchNewsCategories();
			this.fetchWeatherData();
			this.fetchNewsData(this.currentNav, 1);
			this.fetchAdData();

			setInterval(() => {
				this.fetchWeatherData();
			}, 60 * 60 * 1000);

			setInterval(() => {
				this.currentTime = this.formatTime(new Date());
			}, 60000);
		},

		onUnload() {
			if (this.searchTimer) {
				clearTimeout(this.searchTimer);
			}
		}
	}
</script>

<style scoped>
	.page-container {
		background: #f5f5f5;
		min-height: 100vh;
	}

	/* 顶部导航栏 */
	.top-navbar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 32rpx;
		background: linear-gradient(135deg, #007AFF, #00C6FF);
		position: sticky;
		top: 0;
		z-index: 1000;
	}

	.nav-scroll {
		flex: 1;
		white-space: nowrap;
		height: 80rpx;
	}

	.nav-items {
		display: inline-flex;
		align-items: center;
		gap: 40rpx;
		height: 100%;
	}

	.nav-item {
		position: relative;
		padding: 16rpx 0;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-shrink: 0;
	}

	.nav-text {
		font-size: 32rpx;
		font-weight: 600;
		color: rgba(255, 255, 255, 0.8);
		transition: all 0.3s ease;
	}

	.nav-item.active .nav-text {
		color: #ffffff;
		font-weight: 700;
		font-size: 36rpx;
	}

	.nav-indicator {
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 40rpx;
		height: 4rpx;
		background: #ffffff;
		border-radius: 2rpx;
	}

	/* 天气信息 */
	.weather-info {
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		margin-left: 24rpx;
		padding: 12rpx 16rpx;
		border-radius: 16rpx;
		background: rgba(255, 255, 255, 0.2);
		backdrop-filter: blur(10rpx);
		border: 1rpx solid rgba(255, 255, 255, 0.3);
		position: relative;
	}

	.weather-temp {
		font-size: 28rpx;
		color: #ffffff;
		font-weight: 500;
	}

	.weather-location {
		font-size: 24rpx;
		color: rgba(255, 255, 255, 0.9);
		margin-top: 4rpx;
	}

	.weather-refresh {
		position: absolute;
		top: 4rpx;
		right: 4rpx;
		font-size: 20rpx;
		color: rgba(255, 255, 255, 0.8);
		animation: spin 1s linear infinite;
	}

	@keyframes spin {
		from {
			transform: rotate(0deg);
		}

		to {
			transform: rotate(360deg);
		}
	}

	/* 搜索栏 */
	.search-bar {
		padding: 20rpx 32rpx;
		background: #ffffff;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.search-container {
		display: flex;
		align-items: center;
		background: #f8f9fa;
		border-radius: 50rpx;
		padding: 20rpx 28rpx;
		border: 1rpx solid #e9ecef;
	}

	.search-icon {
		font-size: 32rpx;
		color: #6c757d;
		margin-right: 20rpx;
	}

	.search-input {
		flex: 1;
		font-size: 28rpx;
		color: #333;
	}

	.placeholder {
		color: #adb5bd;
		font-size: 28rpx;
	}

	.search-actions {
		display: flex;
		align-items: center;
		gap: 20rpx;
		margin-left: 20rpx;
	}

	.search-action {
		font-size: 24rpx;
		color: #007AFF;
		padding: 10rpx 20rpx;
		background: rgba(0, 122, 255, 0.1);
		border-radius: 20rpx;
		border: 1rpx solid rgba(0, 122, 255, 0.2);
	}

	/* 更新通知 */
	.update-notice {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 24rpx 32rpx;
		background: #e7f3ff;
		border-bottom: 1rpx solid #cfe2ff;
	}

	.notice-text {
		font-size: 26rpx;
		color: #084298;
		font-weight: 500;
	}

	.notice-time {
		font-size: 24rpx;
		color: #6ea8fe;
		margin-left: auto;
		margin-right: 20rpx;
	}

	.notice-close {
		font-size: 32rpx;
		color: #6ea8fe;
		width: 40rpx;
		height: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
		background: rgba(110, 168, 254, 0.1);
	}

	/* 内容区域 */
	.content-wrapper {
		height: calc(100vh - 280rpx);
	}

	.content {
		padding: 0 32rpx;
		max-width: 800rpx;
		margin: 0 auto;
	}

	/* 通用区块样式 */
	.section-title {
		padding: 24rpx 0;
		border-bottom: 2rpx solid #007AFF;
		margin-bottom: 24rpx;
	}

	.section-title-text {
		font-size: 32rpx;
		font-weight: 600;
		color: #007AFF;
	}

	/* 置顶新闻 */
	.top-news-section {
		margin-bottom: 32rpx;
	}

	.top-news-list {
		background: white;
		border-radius: 16rpx;
		padding: 24rpx;
	}

	.top-news-item {
		margin-bottom: 24rpx;
		padding-bottom: 24rpx;
		border-bottom: 1rpx solid #f8f9fa;
	}

	.top-news-item:last-child {
		margin-bottom: 0;
		padding-bottom: 0;
		border-bottom: none;
	}

	/* 普通新闻 */
	.card-wrapper {
		margin-bottom: 24rpx;
	}

	.ad-card {
		margin: 24rpx 0;
	}

	/* 图片样式 */
	.single-image-container {
		margin-top: 20rpx;
	}

	.single-image {
		width: 100%;
		height: 300rpx;
		border-radius: 12rpx;
		background-color: #f8f9fa;
		border: 1rpx solid #e9ecef;
	}

	.multi-images-container {
		display: flex;
		gap: 12rpx;
		margin-top: 20rpx;
	}

	.multi-image-item {
		flex: 1;
	}

	.multi-image {
		width: 100%;
		height: 180rpx;
		border-radius: 8rpx;
		background-color: #f8f9fa;
		border: 1rpx solid #e9ecef;
	}

	/* 空状态 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 120rpx 0;
		background: white;
		border-radius: 16rpx;
		margin: 40rpx 0;
	}

	.empty-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 32rpx;
		opacity: 0.5;
	}

	.empty-text {
		font-size: 28rpx;
		color: #6c757d;
	}

	/* 加载状态 */
	.load-more,
	.no-more {
		text-align: center;
		padding: 40rpx;
		color: #6c757d;
		font-size: 26rpx;
	}

	.load-more-text,
	.no-more-text {
		color: #adb5bd;
	}

	/* 响应式设计 */
	@media (max-width: 768rpx) {
		.top-navbar {
			padding: 16rpx 24rpx;
		}

		.nav-items {
			gap: 32rpx;
		}

		.nav-text {
			font-size: 28rpx;
		}

		.weather-info {
			padding: 10rpx 14rpx;
		}

		.weather-temp {
			font-size: 24rpx;
		}

		.weather-location {
			font-size: 20rpx;
		}

		.search-bar {
			padding: 16rpx 24rpx;
		}

		.update-notice {
			padding: 20rpx 24rpx;
		}

		.content-wrapper {
			height: calc(100vh - 260rpx);
		}

		.content {
			padding: 0 24rpx;
		}

		.section-title-text {
			font-size: 28rpx;
		}
	}
</style>